from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.db import transaction
from .models import CartItem
from .serializers import CartItemSerializer
from apps.product.models import SKU

class CartViewSet(viewsets.ModelViewSet):
    serializer_class = CartItemSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return CartItem.objects.filter(user=self.request.user).select_related('product', 'sku', 'sku__product')

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'code': 200,
            'data': serializer.data
        })

    @action(detail=False, methods=['get'])
    def count(self, request):
        """获取购物车商品总数量"""
        count = self.get_queryset().count()
        return Response({
            'code': 200,
            'message': 'success',
            'data': {
                'count': count
            }
        })

    @action(detail=False, methods=['post'])
    def add(self, request):
        """添加商品到购物车"""
        sku_id = request.data.get('sku_id')
        quantity = int(request.data.get('quantity', 1))

        # 参数验证
        if not sku_id:
            return Response({
                'code': 400,
                'message': '请选择商品规格'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            sku = SKU.objects.select_related('product').get(
                id=sku_id,
                is_active=True,
                product__is_active=True
            )
        except SKU.DoesNotExist:
            return Response({
                'code': 404,
                'message': f'商品规格不存在或已下架 (ID: {sku_id})'
            }, status=status.HTTP_404_NOT_FOUND)
        
        if quantity <= 0:
            return Response({
                'code': 400,
                'message': '数量必须大于0'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        if quantity > sku.stock:
            return Response({
                'code': 400,
                'message': f'库存不足 (当前库存: {sku.stock})'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            with transaction.atomic():
                cart_item, created = CartItem.objects.get_or_create(
                    user=request.user,
                    product=sku.product,
                    sku=sku,
                    defaults={'quantity': quantity}
                )
                
                if not created:
                    cart_item.quantity += quantity
                    if cart_item.quantity > sku.stock:
                        return Response({
                            'code': 400,
                            'message': f'库存不足 (当前库存: {sku.stock}, 购物车已有: {cart_item.quantity - quantity})'
                        }, status=status.HTTP_400_BAD_REQUEST)
                    cart_item.save()

            serializer = self.get_serializer(cart_item)
            return Response({
                'code': 200,
                'message': '添加成功',
                'data': serializer.data
            })
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'添加失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['post'])
    def items_batch(self, request):
        """批量获取购物车商品"""
        ids = request.data.get('ids', [])
        if not ids:
            return Response({
                'code': 400,
                'message': '请指定购物车项ID'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        cart_items = CartItem.objects.filter(
            id__in=ids,
            user=request.user
        ).select_related('product', 'sku', 'sku__product')
        
        data = []
        for item in cart_items:
            if not item.sku:
                continue
            data.append({
                'id': item.id,
                'sku_id': item.sku.id,
                'product_name': item.sku.product.name,
                'sku_name': item.sku.name,
                'image': item.sku.image.url if item.sku.image else item.product.image.url,
                'price': float(item.sku.price),
                'quantity': item.quantity,
                'stock': item.sku.stock
            })
        
        return Response({
            'code': 200,
            'data': data
        })

    @action(detail=False, methods=['post'])
    def update_quantity(self, request):
        """更新购物车商品数量"""
        cart_item_id = request.data.get('cart_item_id')
        quantity = int(request.data.get('quantity', 1))
        
        try:
            cart_item = CartItem.objects.select_related('sku').get(id=cart_item_id, user=request.user)
        except CartItem.DoesNotExist:
            return Response({
                'code': 404,
                'message': '购物车项不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        
        if quantity <= 0:
            cart_item.delete()
            return Response({
                'code': 200,
                'message': '已删除'
            })
        
        if cart_item.sku and quantity > cart_item.sku.stock:
            return Response({
                'code': 400,
                'message': '库存不足'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        cart_item.quantity = quantity
        cart_item.save()
        
        serializer = self.get_serializer(cart_item)
        return Response({
            'code': 200,
            'data': serializer.data
        })

    @action(detail=False, methods=['post'])
    def clear(self, request):
        """清空购物车"""
        CartItem.objects.filter(user=request.user).delete()
        return Response({
            'code': 200,
            'message': '已清空'
        })
